package io.cess.mqtt.demo.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;

/**
 * @author wcl
 * @version 1.0
 * @date 2019/12/14 5:50 下午
 */
@Configuration
public class MqttBeanConfig {

    @Autowired
    private MqttConfig mqttConfig;

    @Bean
    public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, InvalidKeyException {
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        //组装用户名密码
        mqttConnectOptions.setUserName("Signature|" + mqttConfig.getAccessKey() + "|" + mqttConfig.getInstanceId());
        //密码签名
        mqttConnectOptions.setPassword(info.feibiao.live.config.mqtt.Tools.macSignature(mqttConfig.getGroupId()+"@@@"+mqttConfig.getClientId(), mqttConfig.getSecretKey()).toCharArray());
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setKeepAliveInterval(90);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setMqttVersion(MQTT_VERSION_3_1_1);
        //连接超时时间
        mqttConnectOptions.setConnectionTimeout(5000);
        mqttConnectOptions.setKeepAliveInterval(2);
        return mqttConnectOptions;
    }
    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public MqttClientBean getClient() {
        return new MqttClientBean();
    }



}
